package com.imooc.coupon.advice;

import com.imooc.coupon.annotation.IgnoreResponseAdvice;
import com.imooc.coupon.vo.CommonResponse;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * <h1>统一响应</h1>
 * @Author: crowsjian
 * @Date: 2020/5/31 12:17
 */
@RestControllerAdvice
public class CommonResponseDataAdvice implements ResponseBodyAdvice<Object> {
    /**
     * 判断是否需要对响应3进行处理
     * @param returnType
     * @param converterType
     * @return
     */
    @Override
    @SuppressWarnings("all")
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        // 如果当前方法所在的类标识了 @IgnoreResponseAdvice 注解 不需要处理
        if(returnType.getDeclaringClass().isAnnotationPresent(
                IgnoreResponseAdvice.class
        )){
            return false;
        }
        // 如果当前方法 标识了 @IgnoreResponseAdvice 注解 不需要处理
        if(returnType.getMethod().isAnnotationPresent(
                IgnoreResponseAdvice.class
        )){
            return false;
        }
        // 对响应进行处理，执行 beforeBodyWrite 方法
        return true;
    }

    /**
     * 响应返回之前的处理
     * @param body
     * @param returnType
     * @param selectedContentType
     * @param selectedConverterType
     * @param request
     * @param response
     * @return
     */
    @Override
    @SuppressWarnings("all")
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
                                  Class<? extends HttpMessageConverter<?>> selectedConverterType,
                                  ServerHttpRequest request, ServerHttpResponse response) {
        // 定义最终的返回对象
        CommonResponse<Object> commonResponse = new CommonResponse<>(
                0, ""
        );
        // 如果 body 是null，commonResponse 不需要设置data
        if(null == body){
            return commonResponse;
            // 如果 body 已经是CommonResponse，不需要再做处理
        }else if(body instanceof CommonResponse){
            commonResponse = (CommonResponse<Object>)body;
            // 否则，把响应对象作为 commonResponse 的 data 部分
        }else{
            commonResponse.setData(body);
        }
        return commonResponse;
    }
}
